<template>
  <a-modal
    :open="open"
    width="1100px"
    title="医嘱套餐"
    centered
    destroy-on-close
    :ok-button-props="{ disabled: !selectedRowKeys.length, loading: saveLoading }"
    @ok="onOk"
    @cancel="onCancel"
  >
    <div class="flex justify-between">
      <a-input v-model:value="searchkey" class="w-60" placeholder="套餐名称/助记码" allow-clear @keydown.enter="onSearch" />
      <a-space>
        <a-button type="default" @click="onReset">重置</a-button>
        <a-button type="primary" @click="onSearch">搜索</a-button>
      </a-space>
    </div>
    <div class="flex justify-between h-[440px] mt-2">
      <div class="w-60 bg-thin h-full flex flex-col items-center">
        <a-tabs v-model:active-key="suitType" centered>
          <a-tab-pane :key="2" tab="科室" />
          <a-tab-pane :key="0" tab="个人" />
          <a-tab-pane :key="1" tab="全院" />
          <a-tab-pane key="" tab="全部" />
        </a-tabs>
        <SuitList ref="suitListRef" preview :template-type="suitType" :search-key="searchkey" :edit="edit" @select="onSelectSuit" />
      </div>
      <div class="ml-4 flex-auto min-w-0">
        <BaseTable
          :loading="loading"
          :height="390"
          row-key="id"
          :data-source="dataSource"
          column-code="000121"
          :expanded-row-keys="expandedRowKeys"
          :row-selection="{
            selectedRowKeys,
            onChange: onSelectChange,
            getCheckboxProps: (record) => ({
              disabled: record.isChild
            })
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'link'">
              <div class="table-link"></div>
            </template>
            <template v-if="column.dataIndex === 'type'">
              {{ ['临时', '长期', '出院带药'][record.advExecType] }}
            </template>
            <template v-if="column.dataIndex === 'mc'">
              <MedicineInfo :value="{ mc: record?.advName, gg: record?.spc, cj: record?.count + record?.countUnit, pl: record.deliverRoute?.fyff }" />
            </template>
          </template>
        </BaseTable>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import SuitList from '@/views/in-doctor/components/SuitList'
import BaseTable from '@/components/BaseTable'
import useAppStore from '@/store/user'
import useStore from '../../store'

const storeUser = useAppStore()
const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  edit: {
    type: Boolean,
    default: false
  },
  isOperation: {
    type: Boolean,
    default: false
  }
})
const store = useStore()
const searchkey = ref('')
const suitListRef = ref()
const suitType = ref(2)
const selectedRowKeys = ref([])
const selectedRows = ref([])
const expandedRowKeys = ref([])
const selectedSuit = ref(null)
const saveLoading = ref(false)
const params = computed(() => {
  return {
    inpAdviceTemplateId: selectedSuit.value.id,
    zjm: searchkey.value
  }
})
const { loading, dataSource, getData } = useFetch({
  url: '/inp/zyys/getInpAdviceTemplateItemList',
  params,
  onSuccess: (data) => {
    selectedRowKeys.value = []
    selectedRows.value = []
    data.forEach((item) => {
      selectedRowKeys.value.push(item.id)
      if (item.children?.length) {
        expandedRowKeys.value.push(item.id)
        item.children = item.children.map((child) => {
          // selectedRowKeys.value.push(child.id)
          return { ...child, inpAdviceType: props.isOperation ? '1' : '0', isChild: true, inplsh: store.currentPatient.inplsh }
        })
      }
    })
    selectedRows.value = data
  }
})

const onCancel = () => {
  suitType.value = 2
  searchkey.value = ''
  selectedRowKeys.value = []
  selectedRows.value = []
  emit('update:open', false)
}
const onSelectSuit = (select) => {
  selectedSuit.value = select
  getData()
}
watch(
  () => props.open,
  (val) => {
    !val && onCancel()
  }
)
const onSearch = () => {
  suitListRef.value.getData()
}
const onSelectChange = (keys, rows) => {
  selectedRowKeys.value = keys
  selectedRows.value = rows
}
const onReset = () => {
  suitType.value = 2
  searchkey.value = ''
  nextTick(() => suitListRef.value.getData())
}

const onOk = async () => {
  if (!selectedSuit.value) return message.error('请选择套餐')
  saveLoading.value = true
  const laboratoryList = {}
  const paramsArray = selectedRows.value.map((item) => {
    const params = {
      ...item,
      children: item?.children ? item?.children?.map((i) => ({ ...i, id: '' })) : [],
      inplsh: store.currentPatient.inplsh,
      inpAdviceType: props.isOperation ? '1' : '0', //0住院医嘱 1术后医嘱
      brId: store.currentPatient.brId
    }
    if (item.boxType === '检验') {
      const codeList = laboratoryList[item.lisInpTemplateId]?.orderItemCodeList || []
      laboratoryList[item.lisInpTemplateId] = {
        ...item,
        orderItemCodeList: [...codeList, item.advCode]
      }
    }

    delete params.id
    delete params.fid
    return params
    //循环插入
    // await post('/inp/clinicalOrder/doSavePatientClinicalOrder', params)
    // if (index === selectedRows.value.length - 1) {
    //   message.success('开立成功')
    //   emit('success')
    //   onCancel()
    // }
  })
  const { code, msg } = await post('/inp/clinicalOrder/doSavePatientClinicalOrderList', paramsArray)
  saveLoading.value = false
  if (code !== 0) return message.error(msg || '添加套餐失败')
  message.success('开立成功')
  emit('success')
  onCancel()

  for (const key in laboratoryList) {
    if (Object.prototype.hasOwnProperty.call(laboratoryList, key)) {
      const element = laboratoryList[key]
      await post('/lis/LisApply/doSaveLisApply', {
        ...element,
        brId: store.currentPatient.brId,
        applyPath: 1,
        key: store.currentPatient.inplsh,
        applyDoctorId: storeUser.empId,
        applyDeptCode: store.currentPatient?.lastDeptCode
      })
    }
  }
  emit('success')
}
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
:deep(.ant-table-row-indent) {
  display: none;
}
</style>
